﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Transactions;
using System.Xml;
using System.Xml.Serialization;
//using T.FAS.Authority.MetaData.Entity;
using T.FAS.Runtime.Base.Common;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Metadata.Entity;
using T.FAS.Runtime.Metadata.Client;
using T.FAS.Runtime.Metadata.SPI;
using T.FAS.Runtime.Page.Dao;
using T.FAS.Runtime.Metadata.Entity.Page;
using T.FAS.Runtime.Term.Dao;
//using T.FAS.Runtime.Metadata.Entity.Portal;
//using T.FAS.Runtime.RTP.Entity.Portlet;
//using T.FAS.Runtime.Portal.Service;
//using T.FAS.Runtime.Portlet.Service;
using  T.ServiceFramework.ServiceGateway.Client;
using  T.ServiceFramework.ServiceGateway.ClientExtension;

namespace T.FAS.Runtime.Page.Plugin
{
    /// <summary>
    /// Page元数据管理
    /// </summary>
    public class PageRTPManager : AbsMetaDataManager, IMetaDataManager
    {
        readonly PageMetaDataLogic pageMetaDataLogic = new PageMetaDataLogic();
        public void Save(IMetaDataContent metaData)
        {

        }
        public void Delete(IMetaDataContent metaData)
        {

        }
        public void Update(IMetaDataContent metaData)
        {

        }
        public IMetaDataContent GetMetaDataContent(string metaDataId)
        {
            if (string.IsNullOrEmpty(metaDataId))
                throw new FasException(PageExceptionCode.InValidParam, "PageRTPManager.GetMetaDataContent.metaDataId");
            try
            {
                var pageMetaData = pageMetaDataLogic.GetPageRTPMetaData(metaDataId);
                if (pageMetaData != null)
                {
                    pageMetaData.MetaDataID = pageMetaData.ID;
                    pageMetaData.MetaDataCode = pageMetaData.Code;
                    pageMetaData.MetaDataName = pageMetaData.Name;
                    return pageMetaData;
                }
            }
            catch (Exception e)
            {
                throw new FasException(PageExceptionCode.GetFailed, e.ToString());
            }
            return null;
        }
        public string SerializeObject(IMetaDataContent metadata, MetadataSerializeType serializeType)
        {
            if (metadata == null) return string.Empty;
            try
            {
                switch (serializeType)
                {
                    case MetadataSerializeType.XML:
                        var serializer = new XmlSerializer(typeof(PageMetaData));
                        using (var stringWriter = new StringWriter())
                        {
                            using (var writer = XmlWriter.Create(stringWriter))
                            {
                                serializer.Serialize(writer, metadata);
                                return stringWriter.ToString();
                            }
                        }

                    case MetadataSerializeType.JSON:
                    default:
                        return JsonConvert.SerializeObject(metadata);
                }
            }
            catch (Exception e)
            {
                throw new FasException(PageExceptionCode.SerializeFailed, e.ToString());
            }
        }
        public IMetaDataContent DeserializeObject(string metaDataString, MetadataSerializeType serializeType)
        {
            if (string.IsNullOrWhiteSpace(metaDataString))
                return null;
            try
            {
                switch (serializeType)
                {
                    case MetadataSerializeType.XML:
                        var serializer = new XmlSerializer(typeof(PageMetaData));
                        using (var stream = new StringReader(metaDataString))
                        {
                            return serializer.Deserialize(stream) as PageMetaData;
                        }

                    case MetadataSerializeType.JSON:
                    default:
                        PageMetaData pageMetaData = JsonConvert.DeserializeObject<PageMetaData>(metaDataString);
                        pageMetaData.ID = pageMetaData.MetaDataID;
                        pageMetaData.Code = pageMetaData.MetaDataCode;
                        pageMetaData.Name = pageMetaData.MetaDataName;
                        return pageMetaData;
                }
            }
            catch (Exception e)
            {
                throw new FasException(PageExceptionCode.DeserializeFailed, e.ToString());
            }
        }

        public ValidateResult Validate(IMetaDataContent metaData)
        {
            return new ValidateResult();
        }

        public void Release(IMetaDataContent metaData, ReleaseStrategy releaseStrategy)
        {

        }

        public ConflictMessage ConflictCheck(List<IMetaDataContent> releasedMetaData, IMetaDataContent releaseingMetaData)
        {
            return new ConflictMessage();
        }

        public IList<MetaDataExportContent> Export(params IMetaDataContent[] metaDataList)
        {
            if (metaDataList == null)
                throw new FasException(PageExceptionCode.InValidParam, "metaDataList参数为空");
            var contents = new List<MetaDataExportContent>();
            try
            {
                foreach (var item in metaDataList)
                {
                    var pageMetaData = pageMetaDataLogic.GetPageMetaData(item.MetaDataID);
                    if (pageMetaData != null)
                    {
                        pageMetaData.PageRefSchemas = new PageRefSchemaLogic().GetPageRefSchemas(item.MetaDataID);
                        contents.Add(new MetaDataExportContent
                        {
                            Content = this.SerializeObject(pageMetaData, MetadataSerializeType.JSON),
                            ExportType = MetaDataExportType.JSON,
                            MetaDataId = item.MetaDataID,
                            MetaDataType = item.MetaData.MetaTypeID,
                            MetaDataCode = item.MetaData.Code,
                            TenantID = item.MetaData?.TenantId
                        });
                    }
                }
            }
            catch (Exception e)
            {
                throw new FasException(PageExceptionCode.ExportFailed, "导出Page元数据失败" + e.ToString());
            }
            return contents;

        }

        /// <summary>
        /// 元数据保存
        /// </summary>
        /// <param name="metaData"></param>
        public void Import(IList<MetaDataExportContent> contents, MetaDataImportStrategy importStrategy)
        {
            try
            {
                PageRefInstanceLogic instanceLogic = new PageRefInstanceLogic();
                foreach (var exportContent in contents)
                {
                    var parameter = new Dictionary<string, string>();
                    if (importStrategy == MetaDataImportStrategy.Delete)
                    {
                        pageMetaDataLogic.DeletePageMetaData(exportContent.MetaDataId);
                    }
                    else
                    {
                        //ImportSetting importSetting = PortalImporter.GetManageInfo(exportContent, importStrategy);
                        var metaData = this.DeserializeObject(exportContent.Content, MetadataSerializeType.JSON);
                        PageMetaData pageMetaData = (PageMetaData)metaData;
                        if (pageMetaData != null)
                        {
                            using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
                            {
                                pageMetaDataLogic.DeletePageMetaData(exportContent.MetaDataId);

                                if (importStrategy == MetaDataImportStrategy.Replace)
                                {
                                    pageMetaData.ID = exportContent.MetaDataId;
                                    pageMetaData.Code = exportContent.MetaDataCode;
                                    pageMetaData.TenantID = exportContent.TenantID;
                                    pageMetaDataLogic.AddPageMetaData(pageMetaData);
                                }
                                scope.Complete();
                            }
                            instanceLogic.Add(exportContent.MetaDataId, exportContent.MetaDataCode, pageMetaData.PageRefInstances, pageMetaData.PageRefSchemas);
                            /*处理门户&小部件类型的Page导入
                            if (pageMetaData.Header.PageType == PageType.Portlet)
                                PortalImporter.ImportPortlet(pageMetaData, importSetting);
                            else if (pageMetaData.Header.PageType == PageType.Portal)
                                PortalImporter.ImportPortal(pageMetaData, importSetting);
                            */                            
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new FasException(PageExceptionCode.ImportFailed, "导入Page元数据失败" + e.ToString());
            }
        }
        public void Enable(params IMetaDataContent[] metaData)
        {

        }
        public MetaDataCompileResult Compile(IList<IMetaDataContent> metadatas)
        {
            return new MetaDataCompileResult();
        }

        /// <summary>
        /// 获取元数据依赖
        /// </summary>
        /// <param name="metaDataContent"></param>
        /// <returns></returns>
        public List<MetaDataDependency> GetMetaDataDependencys(IMetaDataContent metaDataContent)
        {
            return new List<MetaDataDependency>();
        }
        /// <summary>
        /// 获取元数据更新项
        /// </summary>
        /// <param name="oldMetaData"></param>
        /// <param name="newMetaData"></param>
        /// <returns></returns>
        public MetaDataUpdateSet GetMetaDataUpdateSet(IMetaDataContent oldMetaData, IMetaDataContent newMetaData)
        {
            return null;
        }
        /// <summary>
        /// 更新元数据依赖
        /// </summary>
        /// <param name="metaDataContent"></param>
        /// <param name="updateSet"></param>
        /// <returns></returns>
        public MetaUpdateResult UpdateDependencyMetaData(IMetaDataContent metaDataContent, MetaDataUpdateSet updateSet)
        {
            return null;
        }

        public IRefSchemaEntity BuildRefSchema(IMetaDataContent metaDataContent)
        {
            return null;
        }
        public IRefSchemaEntity DeserializeRefSchemaEntity(string schemaEntityJson)
        {
            return null;
        }
        public IEnumerable<Metadata.Entity.Term> BuildTerms(IMetaDataContent metaDataContent, IEnumerable<Metadata.Entity.Term> terms = null)
        {
            return new List<Metadata.Entity.Term>();
        }

        ValidateResult IMetaDataManager.CompatibleValidate(IMetaDataContent metaData, IMetaDataContent oldMetaData)
        {
            return new ValidateResult { state = "1" };
        }

        public override MetaGenerateCodeResult GenerateCode(IMetaDataContent metadata, bool isInternational)
        {
            throw new NotImplementedException();
        }
    }
}
